package org.iartisan.wechatsdk.mp.material.res

import java.lang.reflect.Type
import java.util.Date

import com.google.common.collect.Lists
import com.google.gson.annotations.JsonAdapter
import com.google.gson.{JsonDeserializationContext, JsonDeserializer, JsonElement}
import org.iartisan.wechatsdk.WechatGsonBuilder

import scala.beans.BeanProperty

/**
  * 获取素材列表 res
  *
  * @author King  2019/5/29
  */
@JsonAdapter(classOf[BatchgetMaterialResAdapter])
class BatchgetMaterialRes {

  @BeanProperty
  var totalCount = 0

  @BeanProperty
  var itemCount = 0

  @BeanProperty
  var items: java.util.List[BatchgetMaterialNewsItem] = _
}

@JsonAdapter(classOf[BatchgetMaterialNewsItemAdapter])
class BatchgetMaterialNewsItem {

  @BeanProperty
  var mediaId: String = _

  @BeanProperty
  var updateTime: Date = _

  @BeanProperty
  var content: java.util.List[MaterialNews] = Lists.newArrayList()

  def addContent(param: MaterialNews): Unit = {
    content.add(param)
  }

}

class BatchgetMaterialResAdapter extends JsonDeserializer[BatchgetMaterialRes] {
  override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BatchgetMaterialRes = {
    val res = new BatchgetMaterialRes
    val jsonObj = json.getAsJsonObject
    res.setTotalCount(jsonObj.get("total_count").getAsInt)
    res.setItemCount(jsonObj.get("item_count").getAsInt)
    if (jsonObj.get("item") != null && !jsonObj.get("item").isJsonNull) {
      val item = jsonObj.getAsJsonArray("item")
      val dataList: java.util.List[BatchgetMaterialNewsItem] = Lists.newArrayList()
      for (i <- 0 until item.size()) {
        val articleInfo = item.get(i)
        val materialNews = WechatGsonBuilder.create.fromJson(articleInfo, classOf[BatchgetMaterialNewsItem])
        dataList.add(materialNews)
      }
      res.setItems(dataList)
    }
    res
  }
}


class BatchgetMaterialNewsItemAdapter extends JsonDeserializer[BatchgetMaterialNewsItem] {
  override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BatchgetMaterialNewsItem = {
    val res = new BatchgetMaterialNewsItem
    val jsonObj = json.getAsJsonObject
    if (jsonObj.get("media_id") != null && !jsonObj.get("media_id").isJsonNull) {
      res.setMediaId(jsonObj.get("media_id").getAsString)
    }
    if (jsonObj.get("update_time") != null && !jsonObj.get("update_time").isJsonNull) {
      res.setUpdateTime(new Date(jsonObj.get("update_time").getAsLong * 1000))
    }
    if (jsonObj.get("content") != null && !jsonObj.get("content").isJsonNull) {
      val newsItem = jsonObj.getAsJsonObject("content")
      res.addContent(WechatGsonBuilder.create.fromJson(newsItem, classOf[MaterialNews]))
    }
    res
  }
}